package com.ecommerce.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 事件推送 Aware：动态更新路由网关 Service
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class DynamicRouteServiceImpl implements ApplicationEventPublisherAware {

    // 写路由定义
    private final RouteDefinitionWriter routeDefinitionWriter;

    // 获取路由定义
    private final RouteDefinitionLocator routeDefinitionLocator;

    // 事件发布对象
    private ApplicationEventPublisher publisher;

    public DynamicRouteServiceImpl(
            RouteDefinitionWriter routeDefinitionWriter,
            RouteDefinitionLocator routeDefinitionLocator
    ) {
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.routeDefinitionLocator = routeDefinitionLocator;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        // 完成事件句柄初始化
        this.publisher = applicationEventPublisher;
    }

    /**
     * 增加路由
     */
    public String addRouteDefinition(RouteDefinition routeDefinition) {
        log.info("gate way route: [{}]", routeDefinition);

        // 保存路由配置并发布
        routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();

        // 发布事件通知给 gateway, 同步新增的路由定义
        this.publisher.publishEvent(new RefreshRoutesEvent(this));

        return "success";
    }

    /**
     * 删除路由
     */
    private String deleteById(String id) {
        try {
            log.info("gateway delete route id [{}]", id);
            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
            // 发布事件通知给 gateway 更新路由定义
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "delete success";
        }catch (Exception exception) {
            log.error("gateway delete route fail: [{}]", exception.getMessage(), exception);
            return "delete fail";
        }
    }

    /**
     * 更新路由
     */
    private String updateByRouteDefinition(RouteDefinition definition) {
        try {
            log.info("gate way update route: [{}]", definition);
            this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
        }catch (Exception exception) {
            return "update fail, not found routeId: " + definition.getId();
        }

        try {
            this.routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
        }catch (Exception exception) {
            return "update route fail";
        }

        return "success";
    }

    /**
     * 更新路由
     */
    public String updateList(List<RouteDefinition> definitions) {
        log.info("gateway update route: [{}]", definitions);

        // 先拿到当前Gateway 中存储的路由定义
        List<RouteDefinition> routeDefinitions = routeDefinitionLocator.getRouteDefinitions().buffer().blockFirst();
        if (!CollectionUtils.isEmpty(routeDefinitions)) {
            // 当前路由如果存在，清除掉所有旧的路由定义
            routeDefinitions.forEach(rd -> {
                    log.info("delete route definition: [{}]", rd);
                    deleteById(rd.getId());
                }
            );
        }

        // 把更新的路由定义同步到gateway
        definitions.forEach(definition -> updateByRouteDefinition(definition));

        return "success";
    }
}
